<template>
  <div
    :class="animate"
    :style="{ height: height, width: width }"
    :id="chartOption.bindingDiv"
    ref="chartDiv"
  />
</template>

<script>
import echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme
import resize from "@/views/dashboard/mixins/resize";

import "../../animate/animate.css";
import { dealWithData, testData,sortsFunAsc } from '../../util/utilFun';
import { parseQueryString, fIsUrL } from "../../util/urlUtil";
import { chartApiBar, remoteChartApi,chartBIanalysis  } from "@/api/tool/datav/chartApi";
import { linkChart } from "../../util/LinkageChart";
import { addOption } from "../../codegen/codegen";
import { getFormsource } from "@/api/tool/datav/formsource";
import VueEvent from "@/views/tool/datav/VueEvent";
const animationDuration = 6000;
import { websocketCommand } from "../../util/websocket.js";

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart"
    },
    width: {
      type: String,
      default: "100%"
    },
    height: {
      type: String,
      default: "100%"
    },
    chartOption: {
      type: Object
    },
    drawingList: {
      type: Array
    }
  },
  data() {
    return {
      chart: null,
      //dataOption: this.chartOption,
      timer: "",
      wsObj: null,
      wsFlag: false,
      wsTimer: "",
      wsValue: null,
      animate: this.className
    };
  },
  watch: {
    width() {
      this.$nextTick(() => {
        this.chart.resize();
      });
    },
    height() {
      this.$nextTick(() => {
        this.chart.resize();
      });
    },
    chartOption: {
      deep: true,
      handler(newVal) {
        this.$nextTick(() => {
          this.setOptions(JSON.parse(JSON.stringify(newVal)));
        });
      }
    },
    "chartOption.theme": {
      handler() {
        if (this.chart != null) {
          this.chart.dispose();
          this.chart = null;
          this.initChart();
        }
      }
    },
    "chartOption.timeout": {
      handler() {
        this.chart.dispose();
        this.chart = null;
        this.initChart();
      }
    },
    "chartOption.dataSourceType": {
      handler(value) {
        //切换数据源重新连接
        if (value !== "websocket") {
          this.wsFlag = false;
          //每次切换数据源恢复原来动画
          this.animate = this.className;
        }
        if (value !== "url") {
          clearTimeout(this.timer);
        } 
      }
    },
    "chartOption.interfaceKey": {
      handler(newValue, oldValue) {
        //初始化不创建连接，改变接口地址重新创建
        if (oldValue !== undefined && oldValue != "") {
          this.wsValue = null;
          this.closeWs();
          this.createWs();
          this.animate = this.className;
        }
      }
    },
    wsFlag: {
      handler(value) {
        if (!value) {
          this.wsValue = null;
          this.closeWs();
        }
      }
    },
    className: {
      handler(value) {
        this.animate = value;
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
    clearTimeout(this.timer);
    if (this.wsFlag) {
      this.closeWs();
    }
  },
  methods: {
    initChart() {
      echarts.registerTheme("customTheme", this.chartOption.theme);
      this.chart = echarts.init(this.$el, "customTheme");
      
      //判断是否开启定时器，当是访问url接口时候并且timeout不为0时候开启定时器
      if (this.timer != "") {
        clearTimeout(this.timer);
      }
      if (
        (this.chartOption.dataSourceType == 'url' || this.chartOption.dataSourceType == 'database') &&
        this.chartOption.timeout > 0
      ) {
        let timerTask = () => {
          this.setOptions(JSON.parse(JSON.stringify(this.chartOption)));
          this.timer = setTimeout(() => {
            timerTask();
          }, this.chartOption.timeout);
        };

        timerTask();
      }else{
        this.setOptions(JSON.parse(JSON.stringify(this.chartOption)));
      }
    },
    setOptions: async function(dataOption) {
      //初始化数据
      //如果不是静态数据就调用接口给staticDataValue赋值
      if (dataOption.dataSourceType == "url") {
        let paramJson = parseQueryString(dataOption.requestParameters);

        let interfaceURL = dataOption.interfaceURL;
        let result = await chartApiBar(
          dataOption.requestMethod,
          interfaceURL,
          paramJson,
          dataOption.token
        );
        
        if(dataOption.newDataFormat == true){
          dataOption.staticDataValue = result;
        }else{
          //数据
          if (result.yAxisData != null) {
            dataOption.staticDataValue[0] = result.yAxisData;
          }
          //分类名称
          if (result.xAxisData != null) {
            dataOption.staticDataValue[1] = result.xAxisData;
          }
        }
        
      } else if (dataOption.dataSourceType == "database") {
         if (dataOption.database.executeSql != undefined && dataOption.database.executeSql != '') {
          
          let result = [];
          if(dataOption.database.sqlType == 'custom'){
          
            result = await chartBIanalysis(dataOption.database);
          }
          if (result.code == 200) {
            dataOption.staticDataValue = result.data;
            //console.log(dataOption.staticDataValue);
          } else {
            alert("操作数据库错误");
          }
        }
      } else if (dataOption.dataSourceType == "form") {
        if (dataOption.formSource != undefined) {
          let response = await getFormsource(dataOption.formSource.id);
          dataOption.staticDataValue = JSON.parse(response.data.formData);
        }
      } else if (dataOption.dataSourceType == "websocket") {
        if (
          dataOption.interfaceKey != undefined &&
          dataOption.interfaceKey != ""
        ) {
          if (!this.wsFlag) {
            this.wsFlag = true;
            this.wsValue = null;
            this.createWs();
          }
          if (this.wsValue != null) {
            dataOption.staticDataValue = this.wsValue;
          }
        }
      }
            
      //数据格式转换
      if(dataOption.newDataFormat == true && !(dataOption.dataSourceType == 'database' && dataOption.bi != null)){
        let staticValue = [];
        let sortData = dealWithData(dataOption.staticDataValue,"series");
        let axisDataTest = [];
        let typeData = [];
        sortData.forEach(element => {
          axisDataTest = [];
          let obj = {"name":element.type};
          element.data = element.data.sort(sortsFunAsc('name'));
          let value = [];
          element.data.forEach(ele => {
            obj.type = ele.type;
            value.push(ele.value);
            axisDataTest.push(ele.name)
          });
          obj.data=value;
          obj.yAxisIndex = element.data[0].yAxisIndex;
          typeData.push(obj);
        });
        staticValue.push(typeData);
        staticValue.push(axisDataTest);
        dataOption.staticDataValue = staticValue;
      }

      //数据值
      let seriesData = [];
      let legend = [];

      let length = dataOption.staticDataValue[0].length - 1;
      for (let sort in dataOption.staticDataValue[0]) {
        let data = {};
        let index = parseInt(sort);

        //data.type = value.type;
        // if(index == 2) {
        // 	data.type = 'line';
        //   data.yAxisIndex = 1;
        //   data.smooth = dataOption.isSmooth;
        // } else {
        //   data.type = 'bar';
        //   data.yAxisIndex = 0;
        // }

        data.type = dataOption.staticDataValue[0][index].type
          ? dataOption.staticDataValue[0][index].type
          : index < length
          ? "bar"
          : "line";

        if (data.type == "line") {
          data.smooth = dataOption.isSmooth;
        }
        //设置数据指示刻度线

        let axisIndex = dataOption.staticDataValue[0][index].yAxisIndex != undefined
              ? dataOption.staticDataValue[0][index].yAxisIndex
              : data.type == "line"
              ? 1
              : 0;

        if(dataOption.isVertical==true){
          data.xAxisIndex =axisIndex;
        }else{
          data.yAxisIndex =axisIndex;
        }

        data.name = dataOption.staticDataValue[0][index].name;
        data.data = dataOption.staticDataValue[0][index].data;
        data.barWidth = dataOption.barWidth;
        //是否显示平均线
        if (dataOption.isMarkLine == true) {
          data.markLine = {
            data: [{ type: "average", name: "平均值" }]
          };
        } else if (
          dataOption.isMarkLine == false ||
          dataOption.isMarkLine == undefined
        ) {
          data.markLine = {};
        }
        //是否显示最大最小值
        if (dataOption.isMarkPoint == true) {
          data.markPoint = {
            data: [
              { type: "max", name: "最大值" },
              { type: "min", name: "最小值" }
            ]
          };
        } else if (
          dataOption.isMarkPoint == false ||
          dataOption.isMarkPoint == undefined
        ) {
          data.markPoint = {};
        }

        //柱状图堆叠展示
        if (dataOption.isStack) {
          if (data.type == "bar") {
            data.stack = "stack";
          }
        }
        seriesData.push(data);
        //图例名称
        legend.push(data.name);
      }
      //图例
      let legendData = {
        data: legend,
        show: dataOption.showLegend,
        x: (dataOption.legendX || 35) + "%",
        y: (dataOption.legendY || 5) + "%",
        orient:
          dataOption.legendOrient == undefined
            ? "horizontal"
            : dataOption.legendOrient,
        textStyle: {
          fontSize:
            dataOption.legendFontSize == undefined
              ? "14"
              : dataOption.legendFontSize,
          color:
            dataOption.legendFontColor == undefined
              ? "#fff"
              : dataOption.legendFontColor
        },
        itemWidth: dataOption.itemWidth || 14,
        itemHeight: dataOption.itemHeight || 8
      };

      //刻度单位
      let yAxisData = dataOption.yAxis;

      if (yAxisData[0].axisLabel.formatter.indexOf("{value}") == -1) {
        yAxisData[0].axisLabel.formatter =
          "{value}" + yAxisData[0].axisLabel.formatter;
      }
      if (yAxisData[1].axisLabel.formatter.indexOf("{value}") == -1) {
        yAxisData[1].axisLabel.formatter =
          "{value}" + yAxisData[1].axisLabel.formatter;
      }

      //分类名称
      let xAxisData = dataOption.xAxis;
      xAxisData[0].data = dataOption.staticDataValue[1];

      let axisTick = {
        show: false
      };

      //设置X轴Y轴刻度不显示
      xAxisData[0].axisTick = axisTick;
      yAxisData[0].axisTick = axisTick;
      yAxisData[1].axisTick = axisTick;

      //设置分隔线样式
      if (dataOption.yAxis[0].splitLine.show) {
        let splitLineStyle = {
          color:
            dataOption.splitLineColor == undefined
              ? "#ccc"
              : dataOption.splitLineColor,
          width:
            dataOption.splitLineWidth == undefined
              ? 1
              : dataOption.splitLineWidth,
          type:
            dataOption.lineStyle == undefined ? "solid" : dataOption.lineStyle
        };
        yAxisData[0].splitLine.lineStyle = splitLineStyle;
      }

      //设置y轴颜色
      yAxisData[1].axisLine.lineStyle.color =
        yAxisData[0].axisLine.lineStyle.color;
      //设置y轴粗细
      yAxisData[0].axisLine.lineStyle.width =
        dataOption.yLineWidth == undefined ? 1 : dataOption.yLineWidth;
      yAxisData[1].axisLine.lineStyle.width =
        dataOption.yLineWidth == undefined ? 1 : dataOption.yLineWidth;

      //设置X轴标签样式
      let xAxisLabel = {
        textStyle: {
          show: true,
          color:
            typeof dataOption.xFontColor == "undefined"
              ? "#fff"
              : dataOption.xFontColor == null
              ? "transparent"
              : dataOption.xFontColor,
          fontSize:
            dataOption.xFontSize == undefined ? 14 : dataOption.xFontSize
        }
      };

      xAxisData[0].axisLabel = xAxisLabel;
      //设置x轴粗细
      xAxisData[0].axisLine.lineStyle.width =
        dataOption.xLineWidth == undefined ? 1 : dataOption.xLineWidth;

      //设置Y轴标签样式
      let textStyle = {
        show: true,
        color:
          typeof dataOption.yFontColor == "undefined"
            ? "#fff"
            : dataOption.yFontColor == null
            ? "transparent"
            : dataOption.yFontColor,
        fontSize: dataOption.yFontSize == undefined ? 14 : dataOption.yFontSize
      };

      yAxisData[0].axisLabel.textStyle = textStyle;
      yAxisData[1].axisLabel.textStyle = textStyle;

      //设置折线粗细
      let lineStyle = {
        normal: {
          width: dataOption.lineWidth == undefined ? 2 : dataOption.lineWidth
        }
      };
      //设置折线标记大小
      seriesData.forEach(element => {
        if (element.type == "line") {
          element.lineStyle = lineStyle;
          element.symbolSize =
            dataOption.lineSymbolSize == undefined
              ? 5
              : dataOption.lineSymbolSize;
        }
      });

      //设置提示框文字样式
      // let tooltipLabel = {

      //     backgroundColor :'transparent',
      //      color: "#fff",

      // }
      dataOption.tooltip.axisPointer.type = "line";

      //设置坐标轴名称样式
      let nameTextStyle = {
        color: dataOption.yFontColor,
        fontSize: dataOption.yFontSize
      };

      yAxisData[0].nameTextStyle = nameTextStyle;
      yAxisData[1].nameTextStyle = nameTextStyle;

      let option = {
        title: dataOption.title,
        tooltip: dataOption.tooltip,
        legend: legendData,
        grid: {
          top: dataOption.gridTop==undefined?"25%":dataOption.gridTop+"%",
          left: dataOption.gridLeft==undefined?"2%":dataOption.gridLeft+"%",
          right: dataOption.gridRight==undefined?"2%":dataOption.gridRight+"%",
          bottom: dataOption.gridBottom==undefined?"5%":dataOption.gridBottom+"%",
          containLabel: true
        },
        toolbox: dataOption.toolbox,
        // xAxis: xAxisData,
        // yAxis: yAxisData,
        series: seriesData
      };

      if(dataOption.isVertical==true){
        option.xAxis=yAxisData;
        option.yAxis=xAxisData;
      }else{
        option.xAxis=xAxisData;
        option.yAxis=yAxisData;
      }

      //执行通用处理函数
      if(dataOption.customData != undefined && dataOption.customData != ""){
        try {
          option = (
          
            //里面为要处理的代码块
          eval(dataOption.customData) 
          
          )(
            option,
            dataOption.staticDataValue,
            this.$refs.chartDiv
          );
        } catch (error) {
          console.log(error)
        }
       } 
        //交互组件配置
      if(dataOption.interactData != undefined && dataOption.interactData != ""){
          try {
              option = (        
              //里面为要处理的代码块
              eval(dataOption.interactData)             
            )(
            option,
            dataOption.staticDataValue,
            this.$refs.chartDiv
            );
          } catch (error) {
            console.log(error)
          }               
       }     

      this.chart.setOption(option, true);

      addOption(dataOption.bindingDiv, option);

      //开启图表联动
      if (dataOption.isLink == true) {
        this.chart.off("click");
        this.chart.on("click", params => {
          //设置参数
          let arrObject = {
            legendName: params.seriesName,
            seriesName: params.name,
            data: params.value
          };

          let arrs = JSON.stringify(arrObject);

          //获取绑定的图表
          let bindList = this.chartOption.bindList;

          if (bindList.length > 0) {
            linkChart(dataOption.arrName, arrs, bindList, this.drawingList);
          }
        });
      }
      //开启图表下钻
      else if (dataOption.isDrillDown == true) {
        this.chart.off("click");
        this.chart.on("click", params => {
          //设置参数
          let arrObject = {
            legendName: params.seriesName,
            seriesName: params.name,
            data: params.value
          };

          let arrs = JSON.stringify(arrObject);

          //获取绑定的图表
          let drillDownChartOption = this.chartOption.drillDownChartOption;

          if (
            drillDownChartOption != undefined &&
            drillDownChartOption != null
          ) {
            this.$set(
              this.chartOption.drillDownChartOption.chartOption,
              "requestParameters",
              "drillParam=" + arrs
            );
            //发送下钻消息
            VueEvent.$emit(
              "drill_down_msg",
              this.chartOption.drillDownChartOption
            );
          }
        });
      } else {
        //关闭图表联动，取消echart点击事件
        this.chart.off("click");
      }
      //开启远程图表控制
      if (dataOption.isRemote == true) {
        if (dataOption.remote != undefined && dataOption.remote != null) {
          this.chart.off("click");
          this.chart.on("click", params => {
            //设置参数
            let arrObject = {
              legendName: params.name,
              data: params.value
            };

            let remoteData = { ...dataOption.remote };
            remoteData.query = arrObject;
            //调用接口
            remoteChartApi(remoteData);
          });
        }
      }
    },
    //  ws连接成功，后台返回的ws数据
    receiveMsg(e) {
      if (e.action == "chat") {
        // console.log('服务端推送',e);
        this.wsValue = JSON.parse(e.result);
        this.setOptions(JSON.parse(JSON.stringify(this.chartOption)));
      }
    },
    // 建立连接、发起ws请求，以心跳方式，向服务端发送数据
    createWs() {
      this.wsObj = new WebSocket(process.env.VUE_APP_WEBSOCKET);
      // 若为对象类型，以回调方式发送
      websocketCommand(
        this.wsObj,
        "create",
        5000,
        this.chartOption.interfaceKey,
        this.sendHeartBeat,
        this.receiveMsg,
        this.reconnectWs,
        this.wsWarning
      );
    },
    // 断网重连，需要处理的逻辑
    reconnectWs() {
      if (this.wsObj) {
        console.log("%c websocket_reconnect", "color:blue");
        this.createWs();
      }
    },
    // 以回调方式向服务端发送(对象类型的)心跳
    sendHeartBeat() {
      if (this.wsTimer != "") {
        clearTimeout(this.wsTimer);
      }

      let wsTimerTask = () => {
        console.log("发送心跳", "ping");
        let obj = { action: "keep", key: this.chartOption.interfaceKey };
        this.wsObj.send(JSON.stringify(obj));
        this.wsTimer = setTimeout(() => {
          wsTimerTask();
        }, parseInt(process.env.VUE_APP_WEBSOCKET_TIMEOUT));
        this.wsWarning();
      };

      wsTimerTask();
    },
    wsWarning() {
      //如果断开连接则显示组件警告动画并清除计数器
      if (this.wsObj.readyState == 3) {
        this.animate = "warning";
        clearTimeout(this.wsTimer);
      }
    },
    closeWs() {
      clearTimeout(this.wsTimer);
      websocketCommand(
        this.wsObj,
        "close",
        5000,
        this.chartOption.interfaceKey,
        this.sendHeartBeat,
        this.receiveMsg,
        this.reconnectWs,
        this.wsWarning
      );
      this.wsObj = null;
    }
  }
};
</script>
